<?php


namespace app\controller\api;


use app\BaseController;
use app\common\exception\ApiException;
use app\model\user\UserModel;
use app\model\user\UserMoneyDetailModel;
use app\model\user\UserWithdrawModel;
use app\service\config\ConfigService;
use app\service\user\UserMoneyDetailService;
use app\service\utils\LockService;
use app\service\utils\QrcodeService;
use app\service\utils\WeiXinService;
use think\facade\Db;

class UserController extends BaseController
{
    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function getUserInfo()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $userInfo = $userInfo->hidden(['password', 'status', 'openid', 'token_valid_time', 'create_time', 'update_time', 'delete_time']);
            $userInfo['avatar'] = !$userInfo['avatar'] ? ConfigService::getConfigValue('logo') : $userInfo['avatar'];
            return $this->success($userInfo);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 设置用户信息
     * @return \think\response\Json
     */
    public function setUserInfo()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $avatar = $this->request->param('avatar', '', 'trim');
            $username = $this->request->param('username', '', 'trim');

            $flag = false;
            if ($avatar) {
                $userInfo->avatar = $avatar;
                $flag = true;
            }
            if ($username) {
                $userInfo->username = $username;
                $flag = true;
            }
            if ($avatar) {
                $userInfo->avatar = $avatar;
                $flag = true;
            }
            if ($flag) {
                $userInfo->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 余额明细
     * @return \think\response\Json
     */
    public function getMoneyDetail()
    {
        try {
            $type = $this->request->param('type', 0);
            if ($type == 0) {
                $where[] = ['type', '<', 100];
            } else {
                $where[] = ['type', '>', 100];
            }
            $list = UserMoneyDetailModel::where($where)
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 分享二维码
     * @return \think\response\Json
     */
    public function getUserQrcode()
    {
        try {
            $userId = $this->request->middleware('userId');
            $userInfo = $this->request->middleware('userInfo');
            if (!$userInfo['qrcode']) {
                $weiXinService = new WeiXinService();
                $path = $weiXinService->getUserQrcode('/pages/tabbar/my?type=0&scene=' . $userId, $userId);
                $userInfo->qrcode = $path;
                $userInfo->save();
            } else {
                $path = $userInfo['qrcode'];
            }
            return $this->success(['qrcode' => $path, 'url' => '']);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 提现
     * @return \think\response\Json
     */
    public function withdraw()
    {
        Db::startTrans();
        try {
            $userId = $this->request->middleware('userId');
            $lockKey = sprintf("withdraw:%d", $userId);
            $lockService = new LockService($lockKey);
            $uniq = uniqid();
            if (!$lockService->acquireLockWithoutRetry($uniq)) {
                throw new ApiException('操作频繁，请稍后重试');
            }
            $money = $this->request->param('amount');

            $configWithdraw = ConfigService::getConfigValue('withdraw_config');
            if ($money < $configWithdraw['min']) {
                throw new ApiException('提现金额最少' . $configWithdraw['min'] . '元');
            }

            $userInfo = UserModel::find($userId);
            $userAmount = $userInfo['money'];
            if ($userAmount < $money) {
                throw new ApiException('余额不足');
            }
            $orderSn = createOrderSn('user_money_detail', 'order_sn', 'TX');
            $detailMoneyService = new UserMoneyDetailService();
            $type = UserMoneyDetailService::WITHDRAW;
            $title = $detailMoneyService->getTypeText($type);
            $detailMoneyService->createLog($title, $userId, $type, $money, 0, $orderSn);

            $rate = bcdiv(bcmul($money, $configWithdraw['rate'], 10), 100, 2);

            $withdraw = new UserWithdrawModel();
            $withdraw->user_id = $userId;
            $withdraw->money = $money;
            $withdraw->rate = $rate;
            $withdraw->real_money = $money - $rate;
            $withdraw->order_sn = $orderSn;
            $withdraw->save();
            Db::commit();
            $lockService->releaseLock($uniq);
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            $lockService->releaseLock($uniq);
            return $this->error($exception);
        }
    }

    /**
     * 我的团队
     * @return \think\response\Json
     */
    public function getMyTeamList()
    {
        try {
            $userId = $this->request->middleware('userId');
            $list = UserModel::where('pid', $userId)
                ->field('username,avatar,create_time')
                ->order('id', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }
}